package com.example.leonard.core.schedue.quartz;

import com.example.leonard.config.QuartzConfig;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class DemoQuartz implements CommandLineRunner {
    @Autowired
    private Scheduler scheduler;
    @Autowired
    private QuartzConfig quartzConfig;

    @Override
    public void run(String... args) throws Exception {
        //创建任务调度工厂
//        StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory();
        //创建任务调度对象
//        Scheduler scheduler = stdSchedulerFactory.getScheduler();
        System.out.println("corn表达式为:" + quartzConfig.getCronSchedule());
        //绑定job
        JobDetail jobDetail = JobBuilder.newJob(DemoQuartzJob.class)
                .withIdentity(DemoQuartzJob.class.getName(), "demoQuartzJob").build();
        //执行时间构建器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzConfig.getCronSchedule());
        //构建执行的tigger
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(DemoQuartzJob.class.getName(), "demoQuartzJob")
                .startNow()
                .withSchedule(cronScheduleBuilder).build();
        try {
            scheduler.scheduleJob(jobDetail, cronTrigger);
            System.out.println("===========定时任务创建成功===================");
            scheduler.start();

        } catch (SchedulerException s) {
            System.out.println("===========定时任务创建失败===============" + s);
            throw new Exception("定时任务创建失败");
        }
    }
}
